//
//  YWTakePhotoController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/9/13.
//

#import "YWTakePhotoController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <CoreMotion/CoreMotion.h>


@interface YWTakePhotoController ()<AVCapturePhotoCaptureDelegate>

@property (weak, nonatomic) IBOutlet UIView *bgView;

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic,strong) AVCaptureDevice *device;
//AVCaptureDeviceInput 代表输入设备，使用AVCaptureDevice 来初始化
@property(nonatomic,strong) AVCaptureDeviceInput *input;
//照片输出流
@property (nonatomic,strong) AVCapturePhotoOutput *output;
//session会话 由它把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic,strong) AVCaptureSession *session;
//图像预览层，实时显示捕获的图像
@property(nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;

- (IBAction)takePhotoClick:(UIButton *)sender;

@property(nonatomic,strong)UIImage *saveImage;

@property(nonatomic,strong)UIImageView *focusView;



// 陀螺仪,检测屏幕方向
@property (nonatomic, strong) CMMotionManager * motionManager;
@property (nonatomic, assign) UIDeviceOrientation deviceOrientation; //保存通过陀螺仪知道的当前手机方向、因为苹果手机可以设置永远不旋转屏幕这样就监测不了方向、所以要使用陀螺仪认为地制造并保存手机方向


@end

@implementation YWTakePhotoController

- (void)startMotionManager{
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    else{
        return;  //假如陀螺仪已经存在就返回不走下面的了、避免重复操作
    }
    _motionManager.deviceMotionUpdateInterval = 1/15.0;
    if (_motionManager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler: ^(CMDeviceMotion *motion, NSError *error){
            
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
            
        }];
    } else {
        NSLog(@"No device motion on device.");
        [self setMotionManager:nil];
    }
}

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x))
    {
        if (y >= 0){
            self.deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
        }
        else{
            self.deviceOrientation = UIDeviceOrientationPortrait;
        }
    }
    else
    {
        if (x >= 0){
            self.deviceOrientation = UIDeviceOrientationLandscapeRight;
        }
        else{
            self.deviceOrientation = UIDeviceOrientationLandscapeLeft;
        }
    }
    
    YWLog(@"orientation:%ld",self.deviceOrientation);
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    // 开启陀螺仪
    [self startMotionManager];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [_motionManager stopDeviceMotionUpdates];
    _motionManager = nil;
}



-(void)handleVideoOrientation{
    //设置拍视频方向
    AVCaptureConnection *captureConnection = [self.output connectionWithMediaType:AVMediaTypeVideo];
    
    //写在开始拍摄的时候就确定视频拍摄方向、而不是写在output的get方法那里
    if (!captureConnection.supportsVideoOrientation) {
        return;
    }
    
    switch (self.deviceOrientation) {
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
            }
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            }
            break;
        case UIDeviceOrientationLandscapeLeft:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            }
            break;
        case UIDeviceOrientationLandscapeRight:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
            }
            break;
       
        default:
            break;
    }
    
    
    //不要用手机的方向了、因为苹果手机可以设置永远不旋转屏幕这样就监测不了方向、所以要使用陀螺仪的方向
//    NSInteger deviceOrientation = [UIDevice currentDevice].orientation;
//    YWLog(@"capture orientation:%ld",deviceOrientation);

    //不需要区分前后摄像头了
//    if(self.input.device.position == AVCaptureDevicePositionFront) {//处理前置摄像头拍摄
//    }
//    else{ //后摄像头处理
//    }
    
}









- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setBackgroundImage:[UIImage imageNamed:@"摄像头反转"] forState:UIControlStateNormal];
    btn.size = CGSizeMake(30, 30);
    [btn addTarget:self action:@selector(toggleCamera) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    //准备拍照
    [self prepareTakePhotoAuthorization];
    
    //开始扫描
    [self startScan];
    
    //添加手势做聚焦
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(focusGesture:)];
    [self.bgView addGestureRecognizer:tap];
    
    
}

- (void)dealloc{
    
    [self.session stopRunning];
}

-(UIImageView *)focusView{
    if(_focusView == nil){
        UIImageView *focusView = [[UIImageView alloc] init];
        focusView.image = [UIImage imageNamed:@"聚焦"];
        [self.bgView addSubview:focusView];
        focusView.bounds = CGRectMake(0, 0, 80, 80);
        focusView.hidden = YES;
        _focusView = focusView;
    }
    return _focusView;
}

-(AVCaptureDevice *)device{
    if(_device == nil){
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _device = device;
        
        //在修改devicce之前一定要调用lock方法,否则会引起崩溃
        if ([device lockForConfiguration:nil]) { // 修改设备的属性，先加锁
            //自动白平衡
            if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
                [device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
            }
            //设置完成后调用unlock
            [device unlockForConfiguration];
        }
        
    }
    return _device;
}
-(AVCaptureDeviceInput *)input{
    if(_input == nil){
        NSError *error = nil;
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
        _input = input;
        
    }
    return _input;
}

-(AVCapturePhotoOutput *)output{
    if(_output == nil){
        AVCapturePhotoOutput *output = [[AVCapturePhotoOutput alloc]init];
        _output = output;
//        AVCaptureConnection *imageConnection = [output connectionWithMediaType:AVMediaTypeVideo];
        
        //这个是写拍摄方向的、按理是在拍摄的时候写不应该写在get方法里
        // 设置 imageConnection 控制相机拍摄图片的角度方向
//        if (imageConnection.supportsVideoOrientation) {
//            imageConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
//        }
    }
    return _output;
}

-(AVCaptureSession *)session{
    if(_session == nil){
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        _session = session;
        //拿到的图像的大小可以自行设定
        if ([session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
            [session setSessionPreset:AVCaptureSessionPreset1280x720];
        }
    }
    return _session;
}

-(AVCaptureVideoPreviewLayer *)previewLayer{
    if(_previewLayer == nil){
        AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer = previewLayer;
    }
    return _previewLayer;
}

- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:gesture.view];
    [self setFocusCursorWithPoint:point];
    CGSize size = self.bgView.bounds.size;
    // focusPoint
    //它的坐标系是先把手机的头向左倒置地横向摆放、然后再以左上角为坐标（0,0）(有“Interest”名字的坐标都是横着来看)
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width);
    if ([self.device lockForConfiguration:nil]) {
        [self.session beginConfiguration];
        /*****必须先设定聚焦位置，在设定聚焦方式******/
        //聚焦点的位置
        if ([self.device isFocusPointOfInterestSupported]) {
            [self.device setFocusPointOfInterest:focusPoint];
        }
        // 聚焦模式
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }else{
            NSLog(@"聚焦模式修改失败");
        }
        //曝光点的位置
        if ([self.device isExposurePointOfInterestSupported]) {
            [self.device setExposurePointOfInterest:focusPoint];
        }
        //曝光模式
        if ([self.device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
            [self.device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
        } else {
            NSLog(@"曝光模式修改失败");
        }
        [self.device unlockForConfiguration];
        [self.session commitConfiguration];
    }
}

-(void)setFocusCursorWithPoint:(CGPoint)point{
     //下面是手触碰屏幕后对焦的效果
    self.focusView.center = point;
    self.focusView.hidden = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            self.focusView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            self.focusView.hidden = YES;
        }];
    }];
    
}

-(void)startScan{
    
    if([self.session canAddInput:self.input] && [self.session canAddOutput:self.output]) {//不是所有的输入输出都能添加进来所以要判断
        
        //会话添加输入输出
        [self.session addInput:self.input];
        [self.session addOutput:self.output];
    }
    else{
        return;
    }
    
    [self.bgView.layer addSublayer:self.previewLayer];
    
    //启动会话，让输入开始采集数据、输出对象、开始处理数据
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
//        [self.session startRunning];
//    });
    [self.session startRunning];
    
}



-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.previewLayer.frame = self.bgView.bounds;
}


-(void)cancelClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//开启拍照权限
-(void)prepareTakePhotoAuthorization{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if(authStatus != AVAuthorizationStatusAuthorized){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        if (granted) {
                           // 申请权限成功
                        } else {
                            // 申请权限失败
                        }
                    });
        }];
    }
}


- (IBAction)takePhotoClick:(UIButton *)sender {
    
    [UIView animateWithDuration:0.1 animations:^{
        self.bgView.alpha = 0;
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.bgView.alpha = 1;
        }];
    }];
    
    //确定拍摄方向
    [self handleVideoOrientation];
    
    
    AVCapturePhotoSettings *set = [AVCapturePhotoSettings photoSettings];
    
    [self.output capturePhotoWithSettings:set delegate:self];

}


-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
    if (!error) {
        NSData *imageData = [photo fileDataRepresentation];
        UIImage *image = [UIImage imageWithData:imageData];
        
        YWLog(@"dd - 拍照成功")
        
        self.saveImage = image;
        
        //在拍摄的一刻我就确定了方向，就不需要在拍摄完再修改图片方向了
        //处理图片的方向
//        self.saveImage = [self handleImageOrientationWithImage:image];
        
        //在市场上主流App中,大多数App都具有存储图片到自己App的相册中
        //判断是否授权保存到相册
        [self judgeIsAuthorized];
        
    }
    
}

//在拍摄的一刻我就确定了方向，就不需要在拍摄完再修改图片方向了、所以这个方法暂时不需要了
-(UIImage *)handleImageOrientationWithImage:(UIImage *)image{
    //1、手机有方向，图片又有方向、
    //2、横竖屏+前后摄像头 = 8种情况设置 （我没有像网上用各种transform、只是粗暴地修改转向）
    //3、假如我修改的image枚举到以后的其它操作有影响的话、我可以用获取上下文绘图的方法获取新的图片就行、这时候新的图片的方向就只能是UIImageOrientationUp的、可以参考YWScanFaceController.m的“case UIImageOrientationUp:”做法、、而且这样好处还可以控制图片的大小不要让它这么大
    YWLog(@"imageOrientation:%ld",image.imageOrientation);
    NSInteger deviceOrientation = [UIDevice currentDevice].orientation;
    YWLog(@"orientation:%ld",deviceOrientation);

    //处理前置摄像头拍摄
    if(self.input.device.position == AVCaptureDevicePositionFront) {
        
        switch (deviceOrientation) {
            case UIDeviceOrientationUnknown:
            case UIDeviceOrientationPortrait:
            case UIDeviceOrientationFaceUp:
            case UIDeviceOrientationFaceDown:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationLeftMirrored];
                }
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationRightMirrored];
                }
                break;
            case UIDeviceOrientationLandscapeLeft:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationDownMirrored];
                }
                break;
            case UIDeviceOrientationLandscapeRight:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationUpMirrored];
                }
                break;
           
                
            default:
                break;
        }
        
        
        

    }
    else{ //后摄像头处理
        
        switch (deviceOrientation) {
            case UIDeviceOrientationUnknown:
            case UIDeviceOrientationPortrait:
            case UIDeviceOrientationFaceUp:
            case UIDeviceOrientationFaceDown:
                {
                    image = image; //图片默认的方向是right
                }
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationLeft];
                }
                break;
            case UIDeviceOrientationLandscapeLeft:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationUp];
                }
                break;
            case UIDeviceOrientationLandscapeRight:
                {
                    
                    image = [[UIImage alloc]initWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationDown];
                }
                break;
           
                
            default:
                break;
        }
        
    }
    
    YWLog(@"chnageImageOrientation:%ld",image.imageOrientation);
    
    return image;
}



//判断是否授权保存到相册
-(void)judgeIsAuthorized{
      // 1.获取用户授权状态,状态有四种
        // 1) PHAuthorizationStatusNotDetermined  不确定
        // 2)  PHAuthorizationStatusRestricted, 家长控制,拒绝
        // 3)  PHAuthorizationStatusDenied, 拒绝
        // 4) PHAuthorizationStatusAuthorized 授权
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
     // 2.判断用户的授权状态
        if (status == PHAuthorizationStatusNotDetermined) {
                // 如果状态是不确定的话,block中的内容会等到授权完成再调用
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                // 授权完成就会调用
                if (status == PHAuthorizationStatusAuthorized) {
                //调用存储图片的方法
                    [self savePhoto];
                }
            }];
            //如果允许访问
        } else if (status == PHAuthorizationStatusAuthorized) {
            //调用存储图片的方法
            [self savePhoto];
            //如果权限是拒绝
        } else {
            // 使用第三方框架,弹出一个页面提示用户去打开授权
           // [SVProgressHUD showInfoWithStatus:@"进入设置界面->找到当前应用->打开允许访问相册开关"];
        }
    
}



 
//保存图片的方法
-(void)savePhoto{
    //修改系统相册用PHPhotoLibrary单例,调用performChanges,否则苹果会报错,并提醒你使用
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        // 调用判断是否已有该名称相册
       PHAssetCollection *assetCollection = [self fetchAssetColletion:
    @"YWPhotoEditMaster"];
        //创建一个操作图库的对象
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        
        if (assetCollection) {
            // 已有相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 1.创建自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"YWPhotoEditMaster"];
        }
        
        // 2.保存你需要保存的图片到系统相册(这里保存的是self.saveImage的图片)
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:self.saveImage];
        
        // 3.把创建好图片添加到自己相册
        //这里使用了占位图片,为什么使用占位图片呢
        //这个block是异步执行的,使用占位图片先为图片分配一个内存,等到有图片的时候,再对内存进行赋值
        PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
        [assetCollectionChangeRequest addAssets:@[placeholder]];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        //弹出一个界面提醒用户是否保存成功
        if (error) {
            //[SVProgressHUD showErrorWithStatus:@"保存失败"];
        } else {
           // [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        }
        
        
    }];
}

//该方法获取在图库中是否已经创建该App的相册
//该方法的作用,获取系统中所有的相册,进行遍历,若是已有相册,返回该相册,若是没有返回nil,参数为需要创建  的相册名称
-(PHAssetCollection *)fetchAssetColletion:(NSString *)albumTitle{
    // 获取所有的相册
    PHFetchResult *result = [PHAssetCollection           fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //遍历相册数组,是否已创建该相册
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:albumTitle]) {
            return assetCollection;
        }
    }
    return nil;
}

//切换摄像头
- (void)toggleCamera{
   
    [UIView transitionWithView:self.bgView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        
            AVCaptureDevicePosition position = self.input.device.position;
               AVCaptureDevice *newVideoDevice = nil;
               if (position == AVCaptureDevicePositionBack) {
                   newVideoDevice = [self videoDeviceWithPosition:AVCaptureDevicePositionFront];
               } else {
                   newVideoDevice = [self videoDeviceWithPosition:AVCaptureDevicePositionBack];
               }
               NSError *error;
               AVCaptureDeviceInput *newVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:newVideoDevice error:&error];
               if (error) {
                   // 错误处理
                   return;
               }
               [self.session beginConfiguration];
               [self.session removeInput:self.input];
               if ([self.session canAddInput:newVideoInput]) {
                   [self.session addInput:newVideoInput];
                   self.device = newVideoDevice;
                   self.input = newVideoInput;
               } else {
                   [self.session addInput:self.input];
               }
               [self.session commitConfiguration];
            
    } completion:^(BOOL finished) {

    }];
    
}

- (AVCaptureDevice *)videoDeviceWithPosition:(AVCaptureDevicePosition)position {
    AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
    NSArray *devices = discoverySession.devices;
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
            return device;
        }
    }
    return nil;
}



//前置摄像头处理
//- (UIImage*)fixOrientationByCameraLocation:(BOOL)isFront {
//
//    NSLog(@"-------%ld",(long)self.imageOrientation);
//
//    // No-op if the orientation is already correct
//
//    CGAffineTransform transform = CGAffineTransformIdentity;
//
//    if (self.imageOrientation == UIImageOrientationUp) return self;
//
//    // We need to calculate the proper transformation to make the image upright.
//
//    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
//
//    switch (self.imageOrientation) {
//
//        case UIImageOrientationDown:
//
//        case UIImageOrientationDownMirrored:
//
//            transform =CGAffineTransformTranslate(transform, self.size.width, self.size.height);
//
//            transform =CGAffineTransformRotate(transform,M_PI);
//
//            break;
//
//        case UIImageOrientationLeft:
//
//        case UIImageOrientationLeftMirrored:
//
//            transform =CGAffineTransformTranslate(transform,self.size.width,0);
//
//            transform =CGAffineTransformRotate(transform,M_PI_2);
//
//            break;
//
//        case UIImageOrientationRight:
//
//        case UIImageOrientationRightMirrored:
//
//            transform =CGAffineTransformTranslate(transform,0,self.size.height);
//
//            transform =CGAffineTransformRotate(transform, -M_PI_2);
//
//            break;
//
//        case UIImageOrientationUp:
//
//        case UIImageOrientationUpMirrored:
//
//            break;
//
//    }
//
//    switch (self.imageOrientation) {
//
//        case UIImageOrientationUpMirrored:
//
//        case UIImageOrientationDownMirrored:
//
//            transform =CGAffineTransformTranslate(transform,self.size.width,0);
//
//            transform =CGAffineTransformScale(transform, -1,1);
//
//            break;
//
//        case UIImageOrientationLeftMirrored:
//
//        case UIImageOrientationRightMirrored:
//
//            transform =CGAffineTransformTranslate(transform,self.size.height,0);
//
//            transform =CGAffineTransformScale(transform, -1,1);
//
//            break;
//
//        case UIImageOrientationUp:
//
//        case UIImageOrientationDown:
//
//        case UIImageOrientationLeft:
//
//        case UIImageOrientationRight:
//
//            break;
//
//    }
//
//    // Now we draw the underlying CGImage into a new context, applying the transform
//
//    // calculated above.
//
//    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
//
//                                             CGImageGetBitsPerComponent(self.CGImage),0,
//
//                                             CGImageGetColorSpace(self.CGImage),
//
//                                             CGImageGetBitmapInfo(self.CGImage));
//
//    CGContextConcatCTM(ctx, transform);
//
//    switch (self.imageOrientation) {
//
//        case UIImageOrientationLeft:
//
//        case UIImageOrientationLeftMirrored:
//
//        case UIImageOrientationRight:
//
//        case UIImageOrientationRightMirrored:
//
//            // Grr...
//
//            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
//
//            break;
//
//        default:
//
//            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
//
//            break;
//
//    }
//
//    // And now we just create a new UIImage from the drawing context
//
//    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
//
//    UIImage *img = [UIImage imageWithCGImage:cgimg];
//
//    CGContextRelease(ctx);
//
//    CGImageRelease(cgimg);
//
//    returnimg;
//
//}
//
////横屏拍照处理
//- (UIImage*)landscapefixOrientation:(BOOL)isleft {
//
//    CGAffineTransform transform = CGAffineTransformIdentity;
//
//    // No-op if the orientation is already correct
//
//    if (self.imageOrientation == UIImageOrientationUp) {
//
//        if(isleft ==YES) {
//
//            NSLog(@"HOME键在左侧");
//
//            transform =CGAffineTransformTranslate(transform,0,self.size.width);
//
//            transform =CGAffineTransformRotate(transform, -M_PI_2);
//
//        }else{
//
//            NSLog(@"HOME键在右侧");
//
//            transform =CGAffineTransformTranslate(transform,self.size.height,0);
//
//            transform =CGAffineTransformRotate(transform,M_PI_2);
//
//        }
//
//    }else{
//
//    }
//
//    // Now we draw the underlying CGImage into a new context, applying the transform
//
//    // calculated above.
//
//    CGContextRef ctx = CGBitmapContextCreate(NULL,
//
//                                             self.size.height,
//
//                                             self.size.width,
//
//                                             CGImageGetBitsPerComponent(self.CGImage),
//
//                                             0,
//
//                                             CGImageGetColorSpace(self.CGImage),    //CGImageGetColorSpace(self.CGImage)
//
//                                             CGImageGetBitmapInfo(self.CGImage)//CGImageGetBitmapInfo(self.CGImage)
//
//                                             );
//
//  CGImageGetBitmapInfo(self.CGImage));
//
//    CGContextConcatCTM(ctx, transform);
//
//    switch (self.imageOrientation) {
//
//        case UIImageOrientationLeft:
//
//        case UIImageOrientationLeftMirrored:
//
//        case UIImageOrientationRight:
//
//        case UIImageOrientationRightMirrored:
//
//            // Grr...
//
//            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
//
//            break;
//
//        default:
//
//            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
//
//            break;
//
//    }
//
//    // And now we just create a new UIImage from the drawing context
//
//    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
//
//    UIImage *img = [UIImage imageWithCGImage:cgimg];
//
//    CGContextRelease(ctx);
//
//    CGImageRelease(cgimg);
//
//    returnimg;
//
//}
//
//
////基本配置
//#pragma mark - 隐藏电池条
//
//- (BOOL)prefersStatusBarHidden {
//
//    return YES;
//
//}
//
//#pragma mark - 强制竖屏
//
//-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
//
//    return UIInterfaceOrientationMaskPortrait;
//
//}
//
//- (BOOL)shouldAutorotate{
//
//    return NO;
//
//}

@end
